import { createRouter, type RouteComponent, type Router, type RouteRecordRaw } from 'vue-router'
import {
  ascending,
  filterTree,
  formatFlatteningRoutes,
  formatTwoStageRoutes,
  getHistoryMode,
  haveCommonElement,
  initRouter
} from '@/router/utils'
// 导入进度条
import { close, start } from '@/utils/nporgress'
import { buildHierarchyTree } from '@/utils/tree'
import remainingRouter from './modules/remaining'
import pageErrorEvent from '@/event/pageErrorEvent'
import { useUserStoreHook } from '@/stores/modules/user'
import { useMenusStoreHook } from '@/stores/modules/menus'
import { transformI18n } from '@/plugins/i18n'

/** 自动导入全部静态路由，无需再手动引入！匹配 src/router/modules 目录（任何嵌套级别）中具有 .ts 扩展名的所有文件，除了 remaining.ts 文件
 * 如何匹配所有文件请看：https://github.com/mrmlnc/fast-glob#basic-syntax
 * 如何排除文件请看：https://cn.vitejs.dev/guide/features.html#negative-patterns
 */
const modules: Record<string, any> = import.meta.glob(
  ['./modules/**/*.ts', '!./modules/**/remaining.ts'],
  {
    eager: true
  }
)

/** 原始静态路由（未做任何处理） */
const routes: any = []

Object.keys(modules).forEach((key) => {
  routes.push(modules[key].default)
})

/** 导出处理后的静态路由（三级及以上的路由全部拍成二级） */
export const constantRoutes: Array<RouteRecordRaw> = formatTwoStageRoutes(
  formatFlatteningRoutes(buildHierarchyTree(ascending(routes.flat(Infinity))))
)

/** 用于渲染菜单，保持原始层级 */
export const constantMenus: RouteComponent[] = filterTree(
  ascending(routes.flat(Infinity)).concat(...remainingRouter)
)

/** 不参与菜单的路由 */
export const remainingPaths = Object.keys(remainingRouter).map((v) => {
  return remainingRouter[Number(v)].path
})

/** 创建路由实例 */
export const router: Router = createRouter({
  history: getHistoryMode(import.meta.env.VITE_ROUTER_HISTORY) as any,
  routes: constantRoutes.concat(...(remainingRouter as any)),
  strict: true,
  scrollBehavior(to, from, savedPosition) {
    return new Promise((resolve) => {
      if (savedPosition) {
        return savedPosition
      } else {
        if (from.meta.saveSrollTop) {
          const top: number = document.documentElement.scrollTop || document.body.scrollTop
          resolve({ left: 0, top })
        }
      }
    })
  }
})

/** 重置路由 */
export function resetRouter() {
  router.getRoutes().forEach((route) => {
    const { name, meta } = route
    if (name && router.hasRoute(name) && meta?.backstage) {
      router.removeRoute(name)
      router.options.routes = formatTwoStageRoutes(
        formatFlatteningRoutes(buildHierarchyTree(ascending(routes.flat(Infinity))))
      )
    }
  })
}

pageErrorEvent.on('page:error:403', () => {
  router.replace('/403')
})

pageErrorEvent.on('page:error:500', () => {
  router.replace('/500')
})

/** 路由白名单 */
const whiteList = ['/login']

router.beforeEach(async (to, _from, next) => {
  start()
  /** 如果已经登录并存在登录信息后不能跳转到路由白名单，而是继续保持在当前页面 */
  function toCorrectRoute() {
    whiteList.includes(to.fullPath) ? next(_from.fullPath) : next()
  }

  const externalLink = to?.name as string
  if (externalLink) {
    to.matched.some((item) => {
      if (!item.meta.title) return ''
      const Title = 'SimpleAdmin'
      if (Title)
        document.title = `${transformI18n(item.meta.title as any) || item.meta.title}-${Title}`
      else document.title = transformI18n(item.meta.title as any)
    })
  }

  if (useUserStoreHook().accessToken) {
    if (to.meta?.roles && !haveCommonElement(to.meta?.roles, useUserStoreHook().getRole)) {
      next({ path: '/403' })
    }
    //刷新
    if (useMenusStoreHook().menus.length === 0 && to.path != '/login') {
      initRouter().then((router: Router) => {
        router.push({
          path: to.path,
          query: to.query,
          hash: to.hash
        })
      })
    }
  } else {
    if (to.path !== '/login') {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        useUserStoreHook().logout()
      }
    }
  }

  next()
})

router.afterEach(() => {
  close()
})

export default router
